﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.EnterpriseLibrary.Security;
using System.ServiceModel.Activation;
using System.Security.Principal;
using Infrastructure.Aspect.Authorization;

namespace Skynet.BusinessLogic.BusinessComponents
{
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class BCSecurityQueries : IBCSecurityQueries
    {
        [Dependency]
        public DataAccess.ISecurityRuleRepository SecurityRuleProvider { get; set; }

        [Dependency]
        public IAuthorizationService AuthorizationService { get; set; }

        public bool Validate(string ApplicationName, string ActionName, System.Security.Principal.IPrincipal Principal)
        {
            var rule = SecurityRuleProvider.GetOne(ApplicationName, ActionName);                         
            return this.AuthorizationService.Validate(rule.Rule, Principal);              
        }
        public bool ValidateUsername(string ApplicationName, string ActionName, string UserName)
        {
            try
            {
                GenericIdentity identity = new GenericIdentity(UserName);
                var roles = System.Web.Security.Roles.GetRolesForUser(UserName);  
                GenericPrincipal principal = new GenericPrincipal(identity,  roles);
                return Validate(ApplicationName, ActionName, principal); 
            }
            catch (Exception )
            {
                return false;
            }                       
        }
    }
}
